using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	public class GetRoleDetailQueryHandler : IRequestHandler<GetRoleDetailQuery, RoleDto>
	{
		private readonly IBaseRepository<Role> _roleRepo;
		private readonly IBaseRepository<RolePermission> _rpRepo;

		public GetRoleDetailQueryHandler(IBaseRepository<Role> roleRepo, IBaseRepository<RolePermission> rpRepo)
		{
			_roleRepo = roleRepo;
			_rpRepo = rpRepo;
		}

		public async Task<RoleDto> Handle(GetRoleDetailQuery request, CancellationToken cancellationToken)
		{
			var role = await _roleRepo.GetModel(x => x.RoleId == request.RoleId);
			if (role == null) throw new Exception("角色不存在");
			var pids = _rpRepo.GetAll().Where(x => ((RolePermission)x).RoleId == request.RoleId).Select(x => ((RolePermission)x).PermissionId).ToList();
			return new RoleDto { RoleId = role.RoleId, Name = role.Name, Description = role.Description, IsActive = role.IsActive, CreatedAt = role.CreatedAt, UpdatedAt = role.UpdatedAt, PermissionIds = pids };
		}
	}
}
